package com.wb.adutils.tools

import io.reactivex.*
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import java.lang.Exception
import java.util.concurrent.TimeUnit

object RxUtils {

    fun <T> doObservable(
        callback: (c: ObservableEmitter<T?>) -> Unit,
        success: (T?) -> Unit,
        fail: (Throwable?) -> Unit
    ): Disposable {
        return Observable.create<T?> {
            try {
                callback(it)
            }catch (e:Exception) {
                fail(e)
            }
        }.subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe({
                success(it)
            }, {
                fail(it)
            })
    }

    fun <T> doObservable(
        callback: (c: ObservableEmitter<T?>) -> Unit,
        success: (T?) -> Unit
    ): Disposable {
        return doObservable(callback, success) {

        }
    }

    fun <T> doObservable(callback: (c: ObservableEmitter<T?>) -> Unit): Disposable {
        return doObservable(callback, {}, {})
    }

    fun timer(
        delay: Long,
        exc: (c: Long) -> Unit,
        success: (Long) -> Unit
    ): Disposable {
        return Flowable.timer(delay, TimeUnit.MILLISECONDS)
            .doOnNext {
                exc(it)
            }
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe {
                success(it)
            }
    }
    fun timer(
        delay: Long,
        success: (Long) -> Unit
    ): Disposable {
        return Flowable.timer(delay, TimeUnit.MILLISECONDS)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe {
                success(it)
            }
    }
    fun interval(
        start: Long,
        count: Long,
        delay: Long,
        period: Long,
        success: (Long) -> Unit
    ): Disposable {
        return  Flowable.intervalRange(start, count, delay, period, TimeUnit.MILLISECONDS)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe {
                success(it)
            }
    }
}